package com.heima.controller.common;

import com.heima.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@Slf4j

public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/api/vm-service/sku/fileUpload")

    public String uploadFile(MultipartFile fileName) {
//        获取原始文件名
        String originalFilename = fileName.getOriginalFilename();
//        截取最后一个.xxx
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
 //        拼接时间日期
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
//        生成UUID 拼接后缀,避免重名问题
        String objectName = format + "/" + UUID.randomUUID().toString() + suffixName;
 
        try {
//            返回文件上传路径
            String uploadedPath = aliOssUtil.upload(fileName.getBytes(), objectName);
            return uploadedPath;
        } catch (IOException e) {
            log.info("文件上传失败:{}", e);
            throw new RuntimeException(e);
        }
    }
}